package com.doerit.laptops.action.signin;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;

import com.doerit.laptops.action.AbstractAction;
import com.doerit.laptops.entity.Staff;
import com.doerit.laptops.exception.SessionNotExist;
import com.doerit.laptops.service.impl.StaffServiceImpl;
import com.doerit.laptops.util.SessionKey;

@Scope("prototype")
public class SignInAction extends AbstractAction {

	public static final String EXPIRE = "expire";
	
	@Autowired
	private StaffServiceImpl staffServiceImpl;

	private static final long serialVersionUID = 1L;

	private Staff staff;

	public String showSigninForm() {
		return SUCCESS;
	}

	public String signIn() {
		try {			
			if (staff == null) {
				addActionError(getText("system.user.signin.failed"));
				return INPUT;
			}

			validateSignIn();
			if (hasErrors()) {
				return INPUT;
			}

			staff = staffServiceImpl.signIn(staff.getEmail(), staff.getPassword());
			
			if (staff == null) {
				addActionError(getText("system.user.signin.failed"));
				return INPUT;
				
			} else {
				addSessionUserVariable(staff);
				return SUCCESS;
			}
			
		} catch (Exception e) {
			e.printStackTrace();
			return INPUT;
		}
	}

	public String signOut() {

		try {
			if (verifySessionUser()) {
				removeSessionVariable(SessionKey.SESSION_USER);
			}
		} catch (SessionNotExist e) {
			e.printStackTrace();
			// logger
		}

		return SUCCESS;
	}

	private void validateSignIn() {
				
		if (staff.getEmail().isEmpty()) {
			addFieldError("staff.email",
					getText("system.user.email.empty"));
		}

		if (staff.getPassword().isEmpty()) {
			addFieldError("staff.userPassword",
					getText("system.user.password.empty"));
		}
	}

	public Staff getStaff() {
		return staff;
	}

	public void setStaff(Staff staff) {
		this.staff = staff;
	}

}
